//
//  CardCenterViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/10.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

class CardCenterViewController: KMViewController {
    
    fileprivate let cellId = "cardCenterCell"
    fileprivate let cellId2 = "articleCell"
    
    var imageUrl = ""
    var titleText = ""
    
    fileprivate var titleArray = ["",pinCard,late,bill] //标题数据
    fileprivate var dataArray = [CardCenterModel]() //卡片信息
    fileprivate var pinCardArray = [ArticleModel]() //销卡信息
    fileprivate var lateArray = [ArticleModel]() //账单
    fileprivate var billArray = [ArticleModel]() //逾期

    
    fileprivate var headView : CenterHeadView! //头部视图
    
    fileprivate var footView : CenterFootView! //尾部视图
    
    fileprivate var moreButton : UIButton! //加载更多
    
    fileprivate var page = 1 //页数
    
    
    fileprivate var tableView : UITableView!
    
    init(title:String,imageUrl:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.titleText = title
        self.title = title + cardCenter
        self.imageUrl = imageUrl
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()
        getCardNews()
        getArticleNews(type: pinCard) //销卡
        getArticleNews(type: late) //逾期
        getArticleNews(type: bill) //账单
        
    }
    
    //MARK: 创建TableView
    fileprivate func createTableView() {
        
        headView = CenterHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 80)))
        headView.image = UIImage.imageWithName(self.imageUrl)
        headView.title = self.titleText
        
        footView = CenterFootView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 390)))
        footView.centerDelegate = self
        footView.articleView.text = self.titleText
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        tableView.tableHeaderView = headView
        tableView.tableFooterView = footView
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CardCenterCell.self, forCellReuseIdentifier: cellId)
        tableView.register(ArticleCell.self, forCellReuseIdentifier: cellId2)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
    }
    
    //MARK: 获取卡信息
    fileprivate func getCardNews(bank:String?=nil) {
        
        KMTool.requestMethod(.get, URLString: url_cardCenter, parameters: ["bank":bank ?? self.titleText,"p":self.page], success: { (value, json) in
            
            if self.page == 1 {
                self.dataArray.removeAll()
            }
            
            if let array = json["data"].arrayObject as? [[String:Any]] {
                
                if array.count == 0 {
                    self.moreButton.setTitle(loadAll, for: .normal)
                    return
                }
                
                for item in array {
                    let model = CardCenterModel.setModel(with: item)
                    self.dataArray.append(model)
                }
                
                self.headView.text = json["count_num"].stringValue
                self.moreButton.setTitle(viewMore, for: .normal)
                
                
                self.tableView.reloadSections(NSIndexSet.init(index: 0) as IndexSet, with: .automatic) //刷新第一组数据
            }
            
        }) {
            

        }
        
    }
    
    //MARK: 获取文章信息
    fileprivate func getArticleNews(type:String) {
        
        KMTool.requestMethod(.get, URLString: url_cardArticle, parameters: ["bank":self.titleText,"p":"1","cate":type], success: { (value, json) in
            
            switch type {
            case pinCard:
                self.pinCardArray.removeAll()
            case late:
                self.lateArray.removeAll()
            case bill:
                self.billArray.removeAll()
            default:
                break
            }
            
            if let dic = json.dictionaryObject {
                
                for i in 0...4{
                    if let item = dic["\(i)"] as? [String:Any] {
                        let model = ArticleModel.setModel(with: item)
                        switch type {
                        case pinCard:
                            self.pinCardArray.append(model)
                        case late:
                            self.lateArray.append(model)
                        case bill:
                            self.billArray.append(model)
                        default:
                            break
                        }
                        
                    }else{
                        break
                    }
                }
                
                switch type {
                case pinCard:
                    //刷新第2组
                    self.tableView.reloadSections(NSIndexSet.init(index: 1) as IndexSet, with: .automatic)
                case late:
                    //刷新第3组
                    self.tableView.reloadSections(NSIndexSet.init(index: 2) as IndexSet, with: .automatic)
                case bill:
                    //刷新第4组
                    self.tableView.reloadSections(NSIndexSet.init(index: 3) as IndexSet, with: .automatic)
                default:
                    break
                }
                
                
            }
            
        }) {
            
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension CardCenterViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return titleArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        switch section {
        case 0:
            return dataArray.count
        case 1:
            return pinCardArray.count
        case 2:
            return lateArray.count
        case 3:
            return billArray.count
        default:
            return 0
           
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return RATIO_H(maxNum: 140)
        }else {
            return RATIO_H(maxNum: 100)
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            return 0
        }else{
           return RATIO_H(maxNum: 40)
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        if section == 0 {
            return RATIO_H(maxNum: 30)
        }else{
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        if section == 0 {
            
            moreButton = UIButton.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 30)))
            moreButton.backgroundColor = UIColor.mineColor()
            moreButton.setTitle(viewMore, for: .normal)
            moreButton.setTitleColor(UIColor.black, for: .normal)
            moreButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
            moreButton.addTarget(self, action: #selector(loadMoreAction(sender:)), for: .touchUpInside)
            return moreButton
        }else{
            return UIView()
        }
        
        
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
       
            let heaView = CardTypeView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 40)))
            heaView.text = self.titleText + creditCard + titleArray[section]
            heaView.moreButton.tag = section
            heaView.moreButton.addTarget(self, action: #selector(moreArticle(sender:)), for: .touchUpInside)
            return heaView
      
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? CardCenterCell
            cell?.model = dataArray[indexPath.row]
            cell?.requestBtn.tag = indexPath.row
            cell?.requestBtn.addTarget(self, action: #selector(freeApplication(sender:)), for: .touchUpInside)
            return cell!
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: cellId2, for: indexPath) as? ArticleCell
            switch indexPath.section {
            case 1:
                cell?.model = pinCardArray[indexPath.row]
            case 2:
                cell?.model = lateArray[indexPath.row]
            case 3:
                cell?.model = billArray[indexPath.row]
            default:
                break
            }
            return cell!
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        var urlString  = ""
        var title = ""
        
        if indexPath.section == 0 {
            
            urlString = "https://m.kameng98.com/mobile/details/i" + dataArray[indexPath.row].id!
            title = dataArray[indexPath.row].credit_name!
            let webVC = WebViewController.init(urlString: urlString, title: title)
            self.navigationController?.pushViewController(webVC, animated: true)
            
        }else{
            
            switch indexPath.section {
            case 1:
                urlString = "https://www.kameng98.com/posts/" + pinCardArray[indexPath.row].id!
            case 2:
                urlString = "https://www.kameng98.com/posts/" + lateArray[indexPath.row].id!
            case 3:
                urlString = "https://www.kameng98.com/posts/" + billArray[indexPath.row].id!
            default:
                break
            }
            
            
            title = self.titleText + creditCard + titleArray[indexPath.section]
            let webVC = WebViewController.init(urlString: urlString, title: title)
            webVC.removeElements = ["mblock mblocks","crumbs mblock","mfooter mblock footer1"]
            self.navigationController?.pushViewController(webVC, animated: true)
        }
        
        
    }
    
    //MARK: 免费申请
    @objc fileprivate func freeApplication(sender:UIButton) {
        
        var urlString = ""
        
        let model = dataArray[sender.tag]
        if model.app_apply_access != "" {
            urlString = model.app_apply_access!
        }else if model.m_apply_access != "" {
            urlString = model.m_apply_access!
        }else if model.apply_access != "" {
            urlString  = model.apply_access!
        }
        
        
        if urlString == "" {
            return
        }
        
        KMTool.generateRecords(idString: model.id!)
        
        let webVC = WebViewController.init(urlString: urlString, title: dataArray[sender.tag].credit_name)
        self.navigationController?.pushViewController(webVC, animated: true)
    }
    
    //MARK: 加载更多
    @objc fileprivate func loadMoreAction(sender:UIButton) {
        
        self.moreButton.setTitle(loadHard+"...", for: .normal)
        self.page += 1
        self.getCardNews()
    }
    
    //MARK: 查看更多文章
    @objc fileprivate func moreArticle(sender:UIButton) {
        
        let articleVC = ArticleViewController.init(type: titleArray[sender.tag], title: self.titleText)
        self.navigationController?.pushViewController(articleVC, animated: true)
    }
}


extension CardCenterViewController : CenterDelegate {
    
    //MARK: 选择信用卡类型
    func selectCardType(title: String) {
        
        let articleVC = ArticleViewController.init(type: title, title: self.titleText)
        self.navigationController?.pushViewController(articleVC, animated: true)
    }
    
    //MARK: 点击加载
    func touchLoad(title: String) {
        
        var height:CGFloat = 0
        
        if self.footView.centerView.frame.size.height > RATIO_H(maxNum: 300) {
            height = RATIO_H(maxNum: 320)
        }else{
            height = 0
        }
        
        if title == touchMore {
            
            self.footView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 390) + height)
            self.footView.articleView.snp.remakeConstraints { (make) in
                make.top.left.right.equalToSuperview()
                make.height.equalTo(RATIO_H(maxNum: 150))
            }
            
        }else{
            
            self.footView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 510) + height)
            self.footView.articleView.snp.remakeConstraints { (make) in
                make.top.left.right.equalToSuperview()
                make.height.equalTo(RATIO_H(maxNum: 270))
            }

        }
        
        
        
        self.tableView.tableFooterView = self.footView
        
    }
    
    //MARK: 选择信用卡类型
    func selectBankType(title: String,imageUrl:String) {
        
        self.titleText = title
        self.title = title + cardCenter
        self.headView.title = title
        self.headView.image = UIImage.imageWithName(imageUrl)
        self.page = 1
        self.footView.articleView.text = self.titleText
        self.getCardNews(bank: title)
        getArticleNews(type: pinCard) //销卡
        getArticleNews(type: late) //逾期
        getArticleNews(type: bill) //账单
        
    }
    
    //MARK: 加载更多信用卡
    func moreBankCard(title: String) {
        
        var height:CGFloat = 0
        
        if self.footView.articleView.frame.size.height > RATIO_H(maxNum: 200) {
            height = RATIO_H(maxNum: 120)
        }else{
            height = 0
        }
        
        if title == bankCardCenter {
            
            self.footView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 710)+height)
            self.footView.centerView.snp.remakeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(self.footView.articleView.snp.bottom)
                make.height.equalTo(RATIO_H(maxNum: 560))
            }
            
        }else{
            
            self.footView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 390)+height)
            self.footView.centerView.snp.remakeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(self.footView.articleView.snp.bottom)
                make.height.equalTo(RATIO_H(maxNum: 240))
            }
            
        }
        
        self.tableView.tableFooterView = self.footView
        
    }
    
}
